//
//  WmcBaseGuideView.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/7/26.
//

import UIKit

class WmcBaseGuideView: WmcBaseView {

    private(set) lazy var maskedView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        view.layer.mask = shapeLayer
        return view
    }()
    
    private(set) lazy var shapeLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillRule = .evenOdd
        return layer
    }()
    
    var maskFrame: CGRect = .zero {
        didSet {
           didMaskFrameChanged()
        }
    }
    
    var maskCornerRadius: CGFloat? {
        didSet {
            didMaskFrameChanged()
        }
    }
    
    init(maskFrame: CGRect) {
        self.maskFrame = maskFrame
        super.init(frame: .zero)
    }
    
    public required convenience init() {
        self.init(maskFrame: .zero)
    }
    
    
    override func makeUI() {
        super.makeUI()
        backgroundColor = UIColor.clear
        // 遮罩
        addSubview(maskedView)
        maskedView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        didMaskFrameChanged()
    }

}

extension WmcBaseGuideView {
    
    private func didMaskFrameChanged() {
        if maskFrame != .zero {
            let path = UIBezierPath(rect: self.frame)
            let maskPath: UIBezierPath
            if let cornerRadius = maskCornerRadius {
                maskPath = UIBezierPath(roundedRect: maskFrame, cornerRadius: cornerRadius)
            } else {
                maskPath = UIBezierPath(rect: maskFrame)
            }
            path.append(maskPath)
            shapeLayer.path = path.cgPath
        }
    }
}
